import {
  CanvasButton
} from '../component/custombutton';

// bag.js
export class Bag {
  constructor(canvas, width, height, continueCallback) {
    this.canvas = canvas;
    this.context = this.canvas.getContext('2d');
    this.width = width;
    this.height = height;
    this.continueCallback = continueCallback;
    this.userOwn = 0;
    this.totalSkins = 0;
    this.newcurrentSkin = '';
    this.pigImage = [];
    this.button = [];
    this.isAnimating = true;
    this.skinWidth = this.width / 8 * 7;
    this.skinX = (this.width - this.skinWidth) / 2;
    this.skinY = this.height / 3; // 排行榜起始Y坐标
    this.skinHeight = this.height / 5 * 3 - (this.height / 3 - this.height / 5); // 排行榜的高度

    // 每行显示的正方形数量和间隔
    this.numCols = 3;
    this.gap = this.skinWidth / 25;

    // 计算每个正方形的宽度和高度
    this.boxWidth = (this.skinWidth - this.gap * (this.numCols - 1)) / this.numCols;
    this.boxHeight = (this.skinHeight - this.gap * (this.numCols - 1)) / this.numCols;

    this.records = wx.getStorageSync('skinInfo') || [];
    this.itemsPerPage = 9; // 每页显示的记录数
    this.currentPage = 1; // 当前页码
    this.totalPages = Math.ceil(this.records.length / this.itemsPerPage); // 总页数

    // 初始化按钮
    this.onLoadImage(() => {
      this.drawButton();
      this.drawPopup();
    });
        // 添加触摸事件监听
    wx.onTouchStart((event) => this.onTouchStart(event));
    wx.onTouchMove((event) => this.onTouchMove(event));
    wx.onTouchEnd((event) => this.onTouchEnd(event));
  }

  drawButton() {
    let _this = this;
    this.close = {
      type: "text",
      text: "×",
      style: {
        left: this.width / 7 * 6,
        top: this.height / 15 * 3,
        width: this.width / 13,
        height: this.height / 22,
        textColor: "black",
        fontSize: `${this.height / 35}px`
      },
      success(button) {
        _this.button.push(button);
        button.drawButton(_this.context); // 绘制按钮
        button.onTap((res) => {
          _this.isAnimating = false; // 停止动画
          // button.destroy();
          _this.buttonDestroy();
          wx.offTouchStart();
          _this.continueCallback();
        })
      },
    };
    new CanvasButton(this.close);
    
    const sortedRecords = this.records.sort((a, b) => {
      if (a.haveStatus === b.haveStatus) {
        return 0;
      }
      return a.haveStatus ? -1 : 1;
    });
    const startIndex = (this.currentPage - 1) * this.itemsPerPage;
    const endIndex = Math.min(startIndex + this.itemsPerPage, sortedRecords.length);
    sortedRecords.forEach((skin,index) => {
      if(index >= startIndex && index < endIndex) {
      const col = (index % this.itemsPerPage) % this.numCols;
      const row = Math.floor((index % this.itemsPerPage) / this.numCols);

      const x = this.skinX + col * (this.boxWidth + this.gap);
      const y = this.skinY + row * (this.boxHeight + this.gap);

      this.equip = {
        type: "text",
        text: "装备",
        style: {
          left: x,
          top: y + this.boxHeight - this.height / 30,
          width: this.boxWidth,
          height: this.height / 30,
          textColor: "black",
          backgroundColor: "lightgreen",
          fontSize: `${this.height / 45}px`
        },
        success(button) {
          _this.button.push(button);
          button.drawButton(_this.context); // 绘制按钮
          button.onTap((res) => {
            // _this.isAnimating = false; // 停止动画
            wx.showToast({
              title: '皮肤已装备',
            });
            // _this.buttonDestroy();
            _this.hideButton();
            const userSkinsInfo = wx.getStorageSync('skinInfo') || [];
            wx.setStorageSync('currentSkin', skin.skinId);
            userSkinsInfo.forEach((userSkinInfo) => {
              if (userSkinInfo.skinId == skin.skinId) {
                wx.setStorageSync('currentSkinImage', userSkinInfo.skinUrl);
              }
            });
            _this.drawButton();
          })
        },

      };

      this.noequip = {
        type: "text",
        text: "装备",
        style: {
          left: x,
          top: y + this.boxHeight - this.height / 30,
          width: this.boxWidth,
          height: this.height / 30,
          textColor: "black",
          backgroundColor: "lightgrey",
          fontSize: `${this.height / 45}px`
        },
        success(button) {
          _this.button.push(button);
          button.drawButton(_this.context); // 绘制按钮
          button.onTap((res) => {
            // _this.isAnimating = false; // 停止动画
            wx.showToast({
              title: '该皮肤尚未拥有',
            });
          })
        },

      };
      if (this.pigImage[skin.skinId].src === 'https://gitee.com/z-l-ya/game-image/raw/master/images/skins/skin_black.png') {
        new CanvasButton(this.noequip);
      } else {
        if (skin.skinId == wx.getStorageSync('currentSkin')) {
          this.equip.text = '已装备';
          this.equip.style.backgroundColor = 'green';
          new CanvasButton(this.equip);
        } else {
          new CanvasButton(this.equip);
        }
      }
    }
    });
  }

  drawPopup() {
    this.drawModal();
  }

  drawSkinList() {
    let _this = this;
    const modalX = this.skinX;
    const modalY = this.skinY;
    const modalWidth = this.skinWidth;
    const modalHeight = this.skinHeight;

    this.context.clearRect(modalX, modalY, modalWidth, modalHeight);
    this.context.fillStyle = 'white'; // 设置背景颜色
    this.context.fillRect(modalX, modalY, modalWidth, modalHeight);

    const sortedRecords = this.records.sort((a, b) => {
      if (a.haveStatus === b.haveStatus) {
        return 0;
      }
      return a.haveStatus ? -1 : 1;
    });

    sortedRecords.forEach((skin, index) => {
      const startIndex = (this.currentPage - 1) * this.itemsPerPage;
      const endIndex = Math.min(startIndex + this.itemsPerPage, sortedRecords.length);
      if(index >= startIndex && index < endIndex) {
      const col = (index % this.itemsPerPage) % this.numCols;
      const row = Math.floor((index % this.itemsPerPage) / this.numCols);
      const x = this.skinX + col * (this.boxWidth + this.gap);
      const y = this.skinY + row * (this.boxHeight + this.gap);
      this.context.fillStyle = 'black';
      this.context.drawImage(this.pigImage[skin.skinId], x, y, this.boxWidth, this.boxHeight);
      }
    })
  }

  onLoadImage(callback) {
    this.loadedImages = 0;
    const totalImages = this.records.length;

    const checkIfAllLoaded = () => {
      if (this.loadedImages === totalImages && callback) {
        callback();
      }
    };

    const loadImage = (record, index) => {
      const img = wx.createImage();
      img.src = record.skinUrl;
      img.onload = () => {
        this.pigImage[record.skinId] = img;
        this.loadedImages++;
        checkIfAllLoaded();
      };
      img.onerror = () => {
        this.loadedImages++;
        checkIfAllLoaded();
      };
    };

    this.totalSkins = this.records.length;
    this.records.forEach((record, index) => {
      if (record.haveStatus === true) {
        loadImage(record, index);
        this.userOwn++;
      } else {
        const img = wx.createImage();
        img.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/skins/skin_black.png';
        img.onload = () => {
          this.pigImage[record.skinId] = img;
          this.loadedImages++;
          checkIfAllLoaded();
        };
      }
    });
  }

  drawModal() {
    if (this.isAnimating) {
      const modalWidth = this.width / 8 * 7;
      const modalHeight = this.height / 5 * 3;
      const modalX = (this.width - modalWidth) / 2;
      const modalY = (this.height - modalHeight) / 2;

      this.context.fillStyle = 'pink'; // 设置你想要的背景颜色
      this.context.fillRect(modalX, modalY, modalWidth, modalHeight);

      this.context.font = `${this.height / 30}px Arial`;
      this.context.fillStyle = 'black';
      this.context.textAlign = 'center';
      this.context.fillText('背包', this.width / 2, this.height / 13 * 3);

      this.context.font = `${this.height / 50}px Arial`;
      this.context.fillStyle = 'black';
      this.context.textAlign = 'center';
      this.context.fillText('左滑更多', this.width / 6 * 5, this.height / 22 * 7);


      this.context.font = `${this.height / 30}px Arial`;
      this.context.fillStyle = 'black';
      this.context.textAlign = 'center';
      this.context.fillText(`${this.userOwn} / ${this.totalSkins}`, this.width / 2, this.height / 13 * 4);
      this.drawSkinList();
    }
    requestAnimationFrame(this.drawModal.bind(this));
  }

  // 触摸事件处理
  onTouchStart(event) {
    // 计算 modal 区域
    console.log('onTouchStart')
    const modalX = this.skinX;
    const modalY = this.skinY;
    const modalWidth = this.skinWidth;
    const modalHeight = this.skinHeight;
    this.startX = event.touches[0].clientX;
    this.startY = event.touches[0].clientY;
    if (
      this.startX < modalX ||
      this.startX > modalX + modalWidth ||
      this.startY < modalY ||
      this.startY > modalY + modalHeight
    ) {
      this.isTouchInsideModal = false;
    } else {
      this.isTouchInsideModal = true;
    }
  }

  onTouchMove(event) {
    console.log('onTouchMove')
    // 这里只在滑动时检查是否仍在 modal 区域内
    if (!this.isTouchInsideModal) return;
  }

  onTouchEnd(event) {
    console.log('onTouchEnd')
    if (!this.isTouchInsideModal) return;
    const endX = event.changedTouches[0].clientX;
    const endY = event.changedTouches[0].clientY;

    const deltaX = endX - this.startX;
    const deltaY = endY - this.startY;

    // 检测滑动方向
    if (Math.abs(deltaX) > Math.abs(deltaY) && Math.abs(deltaX) > 10) { // 水平方向滑动且滑动距离足够
      if (deltaX < 0) {
        this.nextPage(); // 向左滑动
      } else {
        this.prevPage(); // 向右滑动
      }
    }
  }

  nextPage() {
    if (this.currentPage < this.totalPages) {
      console.log(this.currentPage + '下一页')
      this.currentPage++;
      this.hideButton();
      this.drawButton();

    }
  }

  prevPage() {
    if (this.currentPage > 1) {
      console.log(this.currentPage + '上一页');
      this.currentPage--;
      this.hideButton();
      this.drawButton();
    }
  }

  buttonDestroy() {
    this.button.forEach(bt => {
      bt.destroy();
    });
    // this.button = null;
  }

  hideButton() {
    this.button.forEach(bt => {
      bt.hideButton();
    });
  }
  

}
